package com.nchu.chatserver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nchu.chatserver.dao.MessageDTO;
import com.nchu.chatserver.entity.Message;
import com.nchu.chatserver.entity.User;
import com.nchu.chatserver.mapper.MessageMapper;
import com.nchu.chatserver.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    // 可以添加自定义实现
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Message sendMessage(MessageDTO messageDTO) {
        // 验证发送者和接收者是否存在
        User sender = userMapper.selectById(messageDTO.getSenderId());
        User receiver = userMapper.selectById(messageDTO.getReceiverId());
        if (sender == null || receiver == null) {
            throw new RuntimeException("发送者或接收者不存在");
        }

        // 创建消息实体
        Message message = new Message();
        message.setSenderId(messageDTO.getSenderId());
        message.setReceiverId(messageDTO.getReceiverId());
        message.setContent(messageDTO.getContent());
        message.setIsRead(false);
        message.setCreateTime(LocalDateTime.now());

        // 存储消息
        messageMapper.insert(message);

        // 回填生成的ID到DTO（可选）
        messageDTO.setId(message.getId());
        return message;
    }

    @Override
    public void markAsRead(Integer messageId) {
        Message message = messageMapper.selectById(messageId);
        if (message != null && !message.getIsRead()) {
        message.setIsRead(true);
        messageMapper.updateById(message);
    }
    }
    @Override
    public List<Message> getUnreadMessages(Integer userId) {
        // 构造查询条件
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver_id", userId) // 指定接收者为当前用户
                .eq("is_read", false)     // 指定消息为未读
                .orderByAsc("create_time"); // 按创建时间升序排列

        // 使用 selectList 查询未读消息
        return messageMapper.selectList(queryWrapper);
    }

    @Override
    public List<Message> getAllMessages(Integer userId,Integer contactId) {
        // 构造查询条件
        // 构造查询条件
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("sender_id", userId)
                .eq("receiver_id", contactId)
                .or()
                .eq("sender_id", contactId)
                .eq("receiver_id", userId)
                .orderByAsc("create_time"); // 按创建时间升序排列

        return messageMapper.selectList(queryWrapper);
    }
    public void markMessagesAsRead(Integer userId, Integer contactId) {
        // 构造更新条件：接收者是userId，发送者是contactId，并且状态为未读
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver_id", userId)
                .eq("sender_id", contactId)
                .eq("is_read", false);

        // 创建要更新的字段
        Message updateMessage = new Message();
        updateMessage.setIsRead(true);

        // 执行批量更新
        messageMapper.update(updateMessage, queryWrapper);
    }
}